package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import message.Message;

public class NetworkController {

	private static NetworkController connController = new NetworkController();
	private byte[] buffer = new byte[Message.PACKET_SIZE];
	private String ip;
	private int port;
	private Socket socket;
	private PrintWriter pw;
	BufferedReader br;

	private NetworkController() { }

	public static NetworkController getInstance() {

		if(null == connController) {
			return new NetworkController();
		} else
			return connController;

	}

	public void createSocket(String ip, int port) throws UnknownHostException, IOException {
		this.socket = new Socket(ip, port);
	}

	public Socket getSocket() throws UnknownHostException, IOException {
		socket = new Socket(ip, port);
		return socket;
	}

	public OutputStream getOutputStream() throws IOException {
		return socket.getOutputStream();
	}

	public InputStream getInputStream() throws IOException {
		return socket.getInputStream();
	}

	public void sendMessage(InputStreamReader input) throws IOException {

		pw = new PrintWriter(getOutputStream());
		br = new BufferedReader(input);

		String line = null;
		
		
		while((line = br.readLine())!=null){
			if(line.equals("quit")){break;}
			pw.println(line);
			pw.flush();
		}

	}

	public void close() throws IOException {
		
		br.close();
		pw.close();
		socket.close();
		
	}

}
